<?php
  namespace App\Http\Controllers\Admin;
  use Illuminate\Support\Facades\Input;
  use App\Http\Controllers\Controller;
  use \Illuminate\Http\Request;
  use App\Http\Goods\GoodsModel;
  use DB;
  use Session;
  class GoodsController extends CommonController{
    public function goods_list(){
      $data = DB::table('mo_goods')
            ->leftJoin('mo_cate', 'mo_goods.g_cate_id', '=', 'mo_cate.cate_id')
            ->where(array('g_status'=>1))
            ->paginate(2);
      $goods = new GoodsModel();
      $cate = $goods->cate();
      $arr = array('0','0','0','');
      return view('admin.goods.goods_list',array('data'=>$data,'cate'=>$cate,'arr'=>$arr));
    }
   
    /*
        渲染添加商品信息的页面
    */
    public function goods_add(){
      //调用model
      $model = new GoodsModel();
      $data = $model->cate();
      return view('admin.goods.goods_add',array(
          'data'=>$data,
        ));   
    }
    /*
        添加商品通用信息
    */
    public function add_do(Request $requset){
      //自动验证
        $this->validate($requset , [
          'g_name'          =>'required|max:255',
          'g_cate'          =>'required',
          'g_price'         =>'required|max:255',
          'g_original_price'=>'required',
          'g_reper'         =>'required|numeric',
          'g_desc'          =>'required'
        ],
        [
          'g_name.required'               => '商品名必须填写',
          'g_name.max'                    => '商品名最多填写255个字符（一个中文占用两个字符）',
          'g_cate.required'               => '商品分类必须选择',
          'g_price.required'              =>'商品现价必须填写',
          'g_original_price.required'     =>'商品原价必须填写',
          'g_reper.requird'               =>'商品库存量不能为空',
          'g_reper.numeric'               =>'商品库存量只允许为数字',
          'g_desc.requird'                =>'商品描述不能为空'

        ]
        );
        //接收传递过来的值
        $data = input::all();
        //var_dump($data);die;
        $requset->session()->put('g_name',$data['g_name']);
        if($data['g_huohao'] == ""){
            $data['g_huohao'] = date("Ymd").rand(100,999);
        }
        if($data['g_cate'] == 'w'){
            $title = array('content'=>'请您选择分类','url'=>'goods_add');
            return view('admin.alert',['data'=>$title]); 
        }
          $file = $requset->file('g_img');
          $allowed_extensions = ["png", "jpg", "gif","jpeg","JPG","PNG","GIF","JPEG"];
          $destinationPath = 'admin_style/uploads/'; //public 文件夹下面建 storage/uploads 文件夹
          $extension = $file -> getClientOriginalExtension(); //4、获取上传图片的后缀名
          if(in_array($extension,$allowed_extensions)){
            $data['g_img']= '/'.md5(time()).random_int(5,5).".".$extension;//5、重新命名上传文件名字
            $file->move($destinationPath,$data['g_img']);
            $bool = DB::table('mo_goods')->insert([
              'g_name'            =>$data['g_name'],
              'g_huohao'          =>$data['g_huohao'],
              'g_cate_id'         =>$data['g_cate'],
              'g_price'           =>$data['g_price'],
              'g_original_price'  =>$data['g_original_price'],
              'g_img'             =>$data['g_img'],
              'g_reper'           =>$data['g_reper'],
              'g_boutique'        =>$data['g_boutique'],
              'g_special'         =>$data['g_special'],
              'g_hot'             =>$data['g_hot'],
              'g_putaway'         =>$data['g_putaway'],
              'g_desc'            =>$data['g_desc']
            ]);
            if($bool == true){
              $title = array('content'=>'商品基本信息添加成功','url'=>'goods_list');
              return view('admin.alert',['data'=>$title]); 
            }
          }else{
            $title = array('content'=>'图片格式不正确','url'=>'goods_add');
            return view('admin.alert',['data'=>$title]); 
          } 
    }
    //渲染添加商品属性页面
    public function goods_attr($id){
       $model = new GoodsModel();
       //查询数据库里有没有这个id值如果有就删除
       $row = DB::table('mo_attribute')->where('goods_id','=',$id)->get();
       if(!empty($row)){
          DB::table('mo_attribute')->where(array('goods_id'=>$id))->delete();
       }
       //调用模型查询商品的分类id根据商品的分类id查询这个商品的顶级分类的cate_id
       $type_id = $model->goods_attr($id);
       //根据查询出来的分类id来查询商品属性名
       $data = DB::table('mo_type_name')->where('cate_id','=',$type_id)->get();
       //根据查询出来的属性名的id查出属性值
       foreach ($data as $key => $value) {
        //var_dump($value);
         $attr_value = DB::table('mo_type_value')->where('attrname_id','=',$value->id)->get();
         $attrname[] = $value->attr_name;
         $attr_id[]  = $value->id;
         $attrvalue[]= $attr_value;
        }
        return view('admin.goods.goods_attr',array('goods_id'=>$id,'attrname'=>$attrname,'attrvalue'=>$attrvalue,'attr_id'=>$attr_id));
    }
    //商品属性添加（sku）
    public function goods_attr_do(Request $requset){
      $data         = input::all();
      if(empty($data['id'])){
        $title = array('content'=>'请从新添加商品的属性，您添加的值为空','url'=>'goods_list');
        return view('admin.alert',['data'=>$title]);
      }
      $goods_id     = $data['goods_id'];
      $type_id      = $data['id'];
      //把商品属性的id给存到数据库里
      $attrvalue = "[".$type_id."]";
      $row = DB::table('mo_goods_value')->insert([
            'goods_id'  => $goods_id,
            'attr_value'=> $attrvalue
        ]);
        for($i1 = 0 ; $i1 < count($data['sku1']) ; $i1++){
          $sku[]    = $data['sku1'][$i1];
        }

        for($i2 = 0 ; $i2 < count($data['reper']) ; $i2++){
          $reper[]    = $data['reper'][$i2];
        }
        for($i3 = 0 ; $i3 < count($data['price']) ; $i3++){
          $price[]    = $data['price'][$i3];
        }
      //var_dump($sku);die;
      //把传过来的值存到一个数组里面
      foreach($sku as $k=>$v){
        $attr[$k]['sku']   =$sku[$k];
        $attr[$k]['reper'] =$reper[$k];
        $attr[$k]['price'] =$price[$k];
      }

     //循环数组取出对应的值来存到数据库
      foreach($attr as $k=>$v){
        $table = DB::table('mo_attribute')->insert([
              'goods_id'    =>$goods_id,
              'attribute'   =>$v['sku'],
              'reper'       =>$v['reper'],
              'price'       =>$v['price']
          ]);
      }
      if($table == true){
        $title = array('content'=>'添加商品属性成功','url'=>'goods_list');
        return view('admin.alert',['data'=>$title]);
      }
    }
     //渲染添加商品属性页面
    public function goods_manage(){
      //实例化模型
      $model = new GoodsModel();
      //查询商品顶级分类
      $cate = $model->parent();
      return view('admin.goods.goods_manage',array('cate'=>$cate));
    }
    //查询根据传递过来的cate_id查询这个分类下的属性
    public function attrname($id){
      //实例化模型
      $model = new GoodsModel();
      //调用attrName方法查询出商品属性
      $data = $model->attrName($id);
      echo json_encode($data);
    }
    //渲染增加商品属性值页面
    public function attrname_do($id){
      return view('admin.goods.attrname_do',array('id'=>$id));
    }
    //添加商品属性值
    public function DoAttr(Request $requset){
        $data = input::all();
        $id = $data['id'];
        for($i = 0 ; $i < count($data['attr_value']) ; $i++){
          $attr[]['attr_value']    = $data['attr_value'][$i];
        }
        //判断属性值传递过来的时候是否为空如果为空跳转不让添加
        if(empty($attr[0]['attr_value'])){
          $title = array('content'=>'请您添加属性值','url'=>'goods_manage');
          return view('admin.alert',['data'=>$title]);
        }
        foreach($attr as $k=>$v){
          $row = DB::table('mo_type_value')->insert([
                'attr_value'  =>$v['attr_value'],
                'attrname_id' =>$id
            ]);
        }
        if($row == true){
          $title = array('content'=>'添加商品属性值成功','url'=>'goods_manage');
          return view('admin.alert',['data'=>$title]);
        }
    }
    //查看属性值列表
    public function attr_val($id){
      $data = DB::table('mo_type_value')->where('attrname_id','=',$id)->get();
      return view('admin.goods.attr_val_list',array('data'=>$data));
    }
    //删除属性值
    public function attr_del($id){
        $data = DB::table('mo_type_value')->where(array('id'=>$id))->delete();
        if($data == true){
          return redirect('goods/goods_manage');
        }else{
          return redirect()->back()->withInput()->withErrors('删除失败');
        }
    }
    //删除属性名
    public function attrName_del($id){
        $data = DB::table('mo_type_name')->where(array('id'=>$id))->delete();
        if($data == true){
          return redirect('goods/goods_manage');
        }else{
          return redirect()->back()->withInput()->withErrors('删除失败');
        }
    }
    //添加新分类之后添加商品的属性名、
    public function attr_cate_do(){
      /*//查询顶级分类
      $data = DB::table()*/
      //实例化模型
      $model = new GoodsModel();
      $data = $model->parent();
      return view('admin.goods.attr_cate_do',array('data'=>$data));
    }
    //添加
    public function attrCateDo(){
      $data = Input::all();
      //把值添加到数据库里
      $cate_id = $data['cate'];
      if(empty($cate_id)){
        $title = array('content'=>'请您选择分类','url'=>'attr_cate_do');
        return view('admin.alert',['data'=>$title]);
      }
      for($i = 0 ; $i < count($data['attr_name']) ; $i++){
        $attr[]['attr_name']    = $data['attr_name'][$i];
      }
      foreach($attr as $k=>$v){
        $row = DB::table('mo_type_name')->insert([
              'attr_name'  =>$v['attr_name'],
              'cate_id' =>$cate_id
          ]);
      }
      if($row == true){
        $title = array('content'=>'添加商品属性名成功','url'=>'goods_manage');
        return view('admin.alert',['data'=>$title]);
      }
    }
    //上传商品图片
    public function Uploading(Request $requset){
      //从新添加商品里取出name值
      $name = Session::get('g_name');
      //取出id值
      $id = DB::table('mo_goods')->select('g_id')->where(array('g_name'=>$name,'g_status'=>'1'))->first();
      //var_dump($id);die;
      //接收传递过来的文件
      $file = $requset->file('upload');
      foreach ($file as $key => $value) {
          $extension = $value -> getClientOriginalExtension(); //4、获取上传图片的后缀名
          $allowed_extensions = ["png", "jpg", "gif","jpeg","JPG","PNG","GIF","JPEG"];
          $destinationPath = 'admin_style/uploads/'; //public 文件夹下面建 storage/uploads 文件夹
          if(in_array($extension, $allowed_extensions)){
             $fileName = '/'.md5(time()).random_int(5,5).".".$extension;//5、重新命名上传文件名字
             $value->move($destinationPath, $fileName); 
             //var_dump($id); 
             $bool = DB::table('mo_goods_img')->insert(['i_img'=>$fileName,'g_id'=>$id->g_id]);
              //var_dump($bool);
              if($bool == true){
                 $title = array('content'=>'图片上传成功','url'=>'goods_list');
                 return view('admin.alert',['data'=>$title]); 
              }else{
                $title = array('content'=>'图片上传失败','url'=>'goods_uploading');
                return view('admin.alert',['data'=>$title]); 
              }
          }else{
              $title = array('content'=>'图片格式不正确','url'=>'goods_uploading');
              return view('admin.alert',['data'=>$title]); 
          }
      }
    }









    public function goods_cate(){
      $cate = DB::table('mo_cate')->where(array('parent_id'=>0))->get();
      foreach ($cate as $k => $v) {
        $v->zicate = DB::table('mo_cate')->where(array('parent_id'=>$v->cate_id))->get();
      }
      return view('admin.goods.goods_cate',array('cate'=>$cate));
    }

    public function goods_trash(){
      $data = DB::table('mo_goods')
            ->leftJoin('mo_cate', 'mo_goods.g_cate_id', '=', 'mo_cate.cate_id')
            ->where(array('g_status'=>0))
            ->paginate(2);
      $goods = new GoodsModel();
      $cate = $goods->cate();
      return view('admin.goods.goods_trash',array('data'=>$data,'cate'=>$cate));
    }
   
    public function goods_uploading(){

      return view('admin.goods.goods_uploading');
    }

    public function goods_export(){
      return view('admin.goods.goods_export');
    }

    public function goods_virtual(){
      return view('admin.goods.goods_virtual');
    }

    public function goods_virtual_add(){
      return view('admin.goods.goods_virtual_add');
    }

    public function goods_cateadd(){
      return view('admin.goods.goods_cateadd');
    }

    public function goodsdel($id){
      $res = DB::table('mo_goods')->where(array('g_id'=>$id))->delete();
      if($res){
        return redirect('goods/goods_list');
      }else{
        return redirect()->back()->withInput()->withErrors('删除失败');
      }
    }
    /**
     * 批量软删除
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public function goodsdels($str){
      $data["g_status"] = 0;
      $str = explode(",",$str);
      foreach($str as $v){
          DB::table('mo_goods')->where(["g_id" =>$v])->update($data);
      }
      return redirect('goods/goods_list');
    }
    public function onedels($id){
      $data["g_status"] = 0;
      $res = DB::table('mo_goods')->where(["g_id" =>$id])->update($data);
      return redirect('goods/goods_list');
    }
    /**
     * 批量删除
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public function goods_del($str){
      $str = explode(",",$str);
      foreach($str as $v){
          DB::table('mo_goods')->where(["g_id" =>$v])->delete();
      }
      return redirect('goods/goods_trash');
    }
    /**
     * 单删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function one_del($id){
      $res = DB::table('mo_goods')->where(array('g_id'=>$id))->delete();
      if($res){
        return redirect('goods/goods_trash');
      }else{
        return redirect()->back()->withInput()->withErrors('删除失败');
      }
    }
    /**
     * 批量还原
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public function goods_huan($str){
      $data["g_status"] = 1;
      $str = explode(",",$str);
      foreach($str as $v){
          DB::table('mo_goods')->where(["g_id" =>$v])->update($data);
      }
      return redirect('goods/goods_trash');
    }
    /**
     * 单个还原
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function one_huan($id){
      $data["g_status"] = 1;
      $res = DB::table('mo_goods')->where(["g_id" =>$id])->update($data);
      if($res){
        return redirect('goods/goods_trash');
      }
    }
    /**
     * 即点即搜
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    public function search($arr){
      $arr = explode(',', $arr);
      $where['g_status'] = 1;
      if($arr[1] == 0){
        $where = $where;
      }
      if($arr[1] == 1){
        $where['g_boutique'] = 1;
      }
      if($arr[1] == 2){
        $where['g_special'] = 1;
      }
      if($arr[1] == 3){
        $where['g_hot'] = 1;
      }
      if(!$arr[0] == 0 && $arr[2] == 0){
        $where['g_cate_id'] = $arr[0];
      }else if($arr[0] == 0 && !$arr[2] == 0){
        $where['g_putaway'] = $arr[2];
      }else if(!$arr[0] == 0 && !$arr[2] == 0){
        $where['g_cate_id'] = $arr[0];
        $where['g_putaway'] =$arr[2];
      }else if($arr[0] == 0 && $arr[2] == 0){
        $where = $where;
      }
      $data = DB::table('mo_goods')
          ->leftJoin('mo_cate', 'mo_goods.g_cate_id', '=', 'mo_cate.cate_id')
          ->where($where)
          ->where('g_name', 'like', "%$arr[3]%")
          ->paginate(2);
      $goods = new GoodsModel();
      $cate = $goods->cate();
      return view('admin.goods.goods_list',array('data'=>$data,'cate'=>$cate,'arr'=>$arr));
    }
   public function  selected_goods(Request $request){
    $goods = new GoodsModel();
    if($request->input('is_ajax')){
              $where = "1=1";
     $cate=$request->input('cate_id');
     $request>session()->put('cate_id',$cate);  
     if($cate){
          $where .= " and goods_category_id =".$request->input("cate_id");
        }
    $goods_brand = $request->input('brand_id');
    $request->session()->put('brand_id',$goods_brand);
    if($goods_brand){
          $where .= " and goods_brand =".$request->input("brand_id");
        }
    $goods_name = $request->input('goods_name');
   $request->session()->put('goods_name',$goods_name);
    if($goods_name){
          $where .= " and goods_name like "."'%".$request->input("goods_name")."%'";
        }
      $order_by_name = $request->input('order_by');

    $request->session()->put('order_by',$order_by_name);
      $sort_by = $request->input('sort');
        if($sort_by == 'desc'){
         $sort = 'asc';
        }else{
         $sort ='desc';
       }
    $request->session()->put('sort',$sort_by);
     $data= $goods->selectedData("hb_goods",$where,$order_by_name,$sort_by,5);
     $appendData = $data->appends(array(
            'goods_name'=>$goods_name,
            'cate_id' => $cate,
           'brand_id'=>$goods_brand,
           'order_by'=>$order_by_name,
          'sort' =>$sort_by,
	  'is_ajax'=>1,

        ));
     return view("admin.goods.goods_ajax",array('data'=>$data,'sort'=>$sort));
}else{
    $cate = $goods->selectData('hb_category');
    $data = $goods->selectedData('hb_goods',"1=1",'goods_id','asc',5);
    $brand = $goods->selectData('hb_brand');
    return view("admin.goods.goodsList",array('cate'=>$cate,'data'=>$data,'brand'=>$brand,'selectedcate'=>""));
}
  }
  public function search_goods(Request $request){
     $goods = new GoodsModel();
     $where = "1=1";
     $cate=$request->input('cate_id');
     $request>session()->put('cate_id',$cate);  
     if($cate){
	  $where .= " and goods_category_id =".$request->input("cate_id");
	}
    $goods_brand = $request->input('brand_id');
    $request->session()->put('brand_id',$goods_brand);
    if($goods_brand){
          $where .= " and goods_brand =".$request->input("brand_id");
        }
    $goods_name = $request->input('goods_name');
   $request->session()->put('goods_name',$goods_name);
    if($goods_name){
          $where .= " and goods_name like "."'%".$request->input("goods_name")."%'";
        }
      $order_by_name = $request->input('order_by');
    
    $request->session()->put('order_by',$order_by_name);
      $sort_by = $request->input('sort');
	if($sort_by == 'desc'){
         $sort = 'asc';
        }else{
         $sort ='desc';
       }
    $request->session()->put('sort',$sort_by);
     $data= $goods->selectedData("hb_goods",$where,$order_by_name,$sort_by,5);
     $appendData = $data->appends(array(
	    'goods_name'=>$goods_name,
            'cate_id' => $cate,
	   'brand_id'=>$goods_brand,
	   'order_by'=>$order_by_name,
	  'sort' =>$sort_by,
            
        ));
     return view("admin.goods.goods_ajax",array('data'=>$data,'sort'=>$sort));

  }	
    public function goods_cate_del($id){
      $pid = DB::table('mo_type_name')->select('parent_id')->where(array('cate_id'=>$id))->get();
      if($pid->parent_id == 0){
        $data = DB::table('mo_type_name')->where(array('cate_id'=>$id))->delete();
      }else{
        $title = array('content'=>'顶级分类不能被删除','url'=>'goods_cate');
        return view('admin.alert',['data'=>$title]);
      }
      return redirect('goods/goods_cate');
    }
  }
?>

